<template>
  <div class="followup-drawer">
    <el-drawer v-model="isFollowupDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
      <div class="followup-drawer__header">
        <title-view :title="`${clientDetail.customerName}丨${clientDetail.residence}`"></title-view>
        <svg-icon icon-class="close" size="24" @click="handelClose" />
      </div>
      <div class="followup-drawer__body">
        <div class="body-form" v-loading="isSubmitLoading">
          <el-form ref="followUpFormRef" :model="followForm" :rules="followRules" label-position="top" status-icon>
            <el-form-item label="跟进内容" prop="contentDesc">
              <el-input v-model="followForm.contentDesc" :autosize="{ minRows: 4 }" type="textarea" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="上传图片">
              <ali-oss-upload
                :folder="defaultConfig.fileFolder"
                :fileList="upImagesList"
                :maxSize="10"
                :maxLength="8"
                :accept="accept"
                multiple
                list-type="picture-card"
                @uploadSuccess="uploadSuccess"
                @removeFile="removeFile"
              >
                <template>
                  <span>点击上传</span>
                </template>
              </ali-oss-upload>
              <div class="upload-tip">注：最多可上传8张，单张不超过10M，支持JPG/JPEG/PNG格式</div>
            </el-form-item>
            <div class="body-form__switch">
              <div>
                <span class="body-form__switch__label">下次跟进设置</span>
                <el-switch v-model="followForm.isNextSetting" @change="handleNextSetting"></el-switch>
              </div>
              <div>
                <span class="body-form__switch__label">是否通知客户</span>
                <el-switch v-model="followForm.isNoticeCustomer"></el-switch>
              </div>
            </div>
            <template v-if="followForm.isNextSetting">
              <el-form-item label="下次跟进时间" :rules="{ required: true, message: '请选择下次跟进时间', trigger: 'change' }">
                <el-date-picker
                  v-model="followForm.nextDateTine"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY-MM-DD"
                  time-format="HH:mm:ss"
                  :disabled-date="datePicker.disabledDate"
                  :disabled-hours="datePicker.disabledHour"
                  :disabled-minutes="datePicker.disabledMinute"
                  :disabled-seconds="datePicker.disabledSecond"
                />
              </el-form-item>
              <el-form-item
                label="关联任务"
                prop="stageTaskId"
                :rules="{ required: true, message: '请选择跟进任务', trigger: 'change' }"
              >
                <el-select v-model="followForm.stageTaskId" @change="handleTaskChange($event)">
                  <el-option
                    v-for="item in taskOptions"
                    :key="item.stageTaskId"
                    :label="item.taskName"
                    :value="item.stageTaskId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-form>
          <div class="body-form__buttons">
            <el-button class="buttons-cancel" @click="handelClose" size="default">取消</el-button>
            <el-button class="buttons-confirm" type="primary" @click="handelSubmit" size="default">确定</el-button>
          </div>
        </div>
        <div class="body-record" v-loading="isLogLoading">
          <template v-if="followUpData.length">
            <time-line :list="followUpData" />
          </template>
          <el-empty v-else />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from "vue";
import { dayjs } from "element-plus";
import TimeLine from "./components/TimeLine";
import * as datePicker from "@/utils/disabledOldDate";
import { initFollowForm } from "./config";
import defaultConfig from "@/settings";
import { taskListByCustomerId, clientInfoAndFollow, followLogByCustomerId, addFollowLog } from "@/apis/engineeringManage";

const props = defineProps({
  modelValue: Boolean,
  customerId: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["update:modelValue", "submitFollowLog"]);
const { proxy } = getCurrentInstance();

const isFollowupDrawer = computed({
  get: () => props.modelValue,
  set: value => {
    emit("update:modelValue", value);
  }
});

/**
 * 跟进记录
 */
const isLogLoading = ref(false);
const followUpData = ref([]);
const getFollowLogByCustomerId = async () => {
  try {
    isLogLoading.value = true;
    const { data } = await followLogByCustomerId(props.customerId);
    followUpData.value = data ?? [];
    isLogLoading.value = false;
  } catch (err) {
    isLogLoading.value = false;
    console.log(err);
  }
};

/**
 * 客户详情
 */
const clientDetail = ref({
  residence: "",
  customerName: ""
});
const getClientInfoAndFollow = async () => {
  try {
    const { data } = await clientInfoAndFollow(props.customerId);
    clientDetail.value = data ?? {};
  } catch (err) {
    console.log("客户详情>>>>", err);
  }
};

/**
 * 跟进图片
 */
const upImagesList = ref([]);
const accept = ".jpg,.JPG,.jpeg,.JPEG,.png,.PNG";
const uploadSuccess = data => {
  upImagesList.value.push({ url: data.fileUrl, fileUrl: data.fileUrl });
};
const removeFile = file => {
  upImagesList.value.splice(file.index, 1);
};

/**
 * 下次跟进
 */
const currentFollowTask = ref({});
const taskOptions = ref([]);
const getFollowTaskList = async () => {
  const { data } = await taskListByCustomerId(props.customerId);
  taskOptions.value = data ?? [];
  taskOptions.value?.length && (followForm.value.stageTaskId = taskOptions.value[0].stageTaskId);
};
const handleTaskChange = e => {
  const filterCurrentTask = taskOptions.value.find(item => item.stageTaskId === e);
  currentFollowTask.value.stageTaskId = filterCurrentTask.stageTaskId;
};
const handleNextSetting = e => {
  followForm.value.nextDateTine = e ? dayjs().format("YYYY-MM-DD HH:mm:ss") : "";
  followForm.value.nextTime = followForm.value.nextDateTine;
  e && getFollowTaskList();
};

/**
 * 提交跟进
 */
const isSubmitLoading = ref(false);
const followForm = ref({ ...initFollowForm });
const followRules = {
  contentDesc: [{ required: true, message: "请输入跟进内容", trigger: "blur" }]
};
const handelSubmit = async () => {
  proxy.$refs.followUpFormRef.validate(async valid => {
    if (!valid) {
      return proxy.$modal.msgError("请完善信息");
    }
    try {
      isSubmitLoading.value = true;
      const postFormData = {
        ...followForm.value,
        isNoticeCustomer: followForm.value.isNoticeCustomer ? 1 : 0,
        isNextSetting: followForm.value.isNextSetting ? 1 : 0,
        trackDatetime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        nextContent: followForm.value.contentDesc,
        customerId: props.customerId,
        crmFileCreateVOList: upImagesList.value
      };
      await addFollowLog(postFormData);
      isSubmitLoading.value = false;
      followForm.value = { ...initFollowForm };
      upImagesList.value = [];
      getFollowLogByCustomerId();
    } catch (err) {
      isSubmitLoading.value = false;
      console.log(err);
    }
  });
};
const handelClose = () => {
  followForm.value = { ...initFollowForm };
  upImagesList.value = [];
  isFollowupDrawer.value = false;
};

getClientInfoAndFollow();
getFollowLogByCustomerId();
</script>

<style scoped lang="scss">
@import "followupDrawer";
</style>
